#include "pluginspec.h"


PluginSpec::PluginSpec()
    :state(PluginSpec::Invalid)
{

}

void PluginSpec::ReadInfo(QFileInfo file)
{
    this->name = file.fileName();
    this->size = file.size();
    this->filePath = file.absoluteFilePath();
    state = PluginSpec::Readed;
}

bool PluginSpec::LoadLibrary()
{
    QPluginLoader loader(this->filePath);
    if (!loader.load()) {
        qDebug() << QString(QObject::tr("Load %1 plugin error!")).arg(this->name);
        return false;
    }
    IPlugin *pluginObject = qobject_cast<IPlugin*>(loader.instance());

    plugin = pluginObject;
    state = PluginSpec::Loaded;

    qDebug() << QString(QObject::tr("Load %1 plugin success!")).arg(this->name);
    return true;
}

bool PluginSpec::InitializePlugin()
{
    if (state != PluginSpec::Loaded) {
        return false;
    }
    if (!plugin) {
        return false;
    }

    QStringList arguments;
    QString err;

    if (!plugin->initialize(arguments, &err)) {
        qDebug() << QString(QObject::tr("Initlize %1 plugin error!")).arg(this->name);
        return false;
    }

    qDebug() << QString(QObject::tr("Initlize %1 plugin success!")).arg(this->name);

    qDebug() << err;

    state = PluginSpec::Initialized;
    return true;
}

bool PluginSpec::InitializeExtensions()
{
    if (state != PluginSpec::Initialized) {
        return false;
    }
    if (!plugin) {
        return false;
    }

    QStringList arguments;
    QString err;

    plugin->extensionsInitialized();

    qDebug() << QString(QObject::tr("Initlize Extension %1 plugin success!")).arg(this->name);

    state = PluginSpec::Running;
    return true;
}

void PluginSpec::DeleteLibrary()
{
    state = PluginSpec::Deleted;
}

